﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using RikaScript.Exception;
using RikaScript.Libs.Base;

namespace RikaScript.Libs
{
    [Library(Name = "str", Help = "RikaScript 标准字符串处理类库", Version = "0.1.0")]
    public class StringLib : ScriptLibBase
    {
        [Method]
        public object format(object str, object arg1)
        {
            return str.String().Format(arg1.String());
        }

        [Method]
        public object format(object str, object arg1, object arg2)
        {
            return str.String().Format(arg1.String(), arg2.String());
        }

        [Method(Help = "格式化字符串，将字符串中的{0}{1}{2}替换成对应的参数")]
        public object format(object str, object arg1, object arg2, object arg3)
        {
            return str.String().Format(arg1.String(), arg2.String(), arg3.String());
        }

        [Method(Help = "获取字符串指定位置的字符")]
        public object at(object str, object index)
        {
            return str.String()[(int) index.Long()] + "";
        }

        [Method(Help = "获取子字符串第一次出现的位置")]
        public object indexOf(object str, object substr)
        {
            return str.String().IndexOf(substr.String(), StringComparison.Ordinal);
        }

        [Method(Help = "分隔字符串，返回List")]
        public object split(object str, object by)
        {
            var byStr = by.String();
            if (byStr.Length != 1)
            {
                throw new RuntimeException("分隔字符串所用的符号长度必须为1");
            }

            var ar = str.String().Split(by.String()[0]);
            var res = ar.Cast<object>().ToList();
            return res;
        }

        [Method(Help = "去除两边多余的空字符")]
        public object trim(object str)
        {
            return str.String().Trim();
        }

        [Method(Help = "字符串替换")]
        public object replace(object str, object oldStr, object newStr)
        {
            return str.String().Replace(oldStr.String(), newStr.String());
        }

        [Method(Help = "根据起始位置和长度截取子字符串")]
        public object subString(object str, object start, object len)
        {
            return str.String().Substring((int) start.Long(), (int) len.Long());
        }
    }
}